<?php

session_start();

if (!(isset($_SESSION['login']) && $_SESSION['login'] != '')) {
    $login = "";
    header("Location: login.php");
} else {
    $login = $_SESSION['login'];
}

$errorMessage = "";
$num_rows = 0;
$used = "";

include 'i_functions.php';


if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    $csvCol = $_POST['csvCol'];
    $MapTo = $_POST['MapTo'];
    $TableCol = $_POST['TableCol'];
    $csvCount = $_POST['csvCount'];
    $csvFile = $_POST["csvFile"];
    $TableName = $_POST["TableName"];
    $MapToCol = array();
    //print "<br>" . $csvCount . " columns to map<br>";

    $user_name = "root";
    $pass_word = "haddons";
    $database = "PPI";
    $server = "127.0.0.1";

    $db_handle = mysql_connect($server, $user_name, $pass_word);
    $db_found = mysql_select_db($database, $db_handle);

    if ($db_found) {
        $sql = "LOAD DATA INFILE '" . $csvFile . "' IGNORE ";
        $sql = $sql . " INTO TABLE `" . $TableName . "`";
        $sql = $sql . " FIELDS TERMINATED BY ','";
        $sql = $sql . " LINES TERMINATED BY '\\n'";
        $sql = $sql . " IGNORE 1 LINES (";
        for ($i = 0; $i < $csvCount; $i++) {
            if ($csvCol[$i] <> "") {
                $ColName = $TableCol[$MapTo[$i]];
                $MapToCol[$i] = $ColName;
                if ($ColName == "") {
                    $ColName = "@ignore";
                }
                $sql = $sql . "`" . $ColName . "`";
                if ($i < ($csvCount - 1)) {
                    $sql = $sql . ", ";
                }
            }
        }
        $sql = $sql . " )";
        //$sql = $sql .
        print "<br>" . $sql . "<br>";
// save mapping
        $x = explode(".",$csvFile);
        $x = explode("/",$x[0]);
        $mapID = $x[1] . "_to_" . $TableName;
        $mapcsv = implode(",",$csvCol);
        $mapTbl = implode(",",$MapToCol);
        $mapSQL = "INSERT INTO `PPI`.`csv_map`
            (`ID`, `csvCol`, `TableCol`)
            VALUES ('$mapID', '$mapcsv', '$mapTbl')";
        print "<br>" . $mapSQL;
        $result = mysql_query($mapSQL);
        print "<br>" . $result;
        //
        mysql_close($db_handle);
    }
}
?>